<template>
  <div>
    <DataHead />
    <a-table
      @change="pageChange"
      table-layout="fixed"
      class="mt-4"
      sticky
      :row-selection="{
        selectedRowKeys: table.keys,
        onChange: (k: any[]) => (table.keys = k),
      }"
      bordered
      :loading="table.loading"
      :pagination="{
        pageSize: query.pageSize,
        current: query.pageNum,
        total: query.total,
      }"
      :customRow="customRow"
      :rowKey="table.rowKey"
      :columns="formatColumns(computedColumns)"
      :data-source="table.data"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operation'">
          <a-button type="ghost" class="bg-yellow-300" @click="distribution(record as any)">
            {{ t('下发') }}
          </a-button>
          <a-button type="link" @click="edit(record[table.rowKey])">
            {{ t('编辑') }}
            <EditOutlined />
          </a-button>
        </template>
        <template v-else-if="column.key === 'label'">
          <a-select
            :max-tag-count="1"
            @change="changeGroup(record as any)"
            class="w-full"
            v-model:value="record.label"
            mode="multiple"
            :options="labelOptions"
            allow-clear
          ></a-select>
        </template>
        <template v-else-if="column.key === 'display'">
          <a-dropdown trigger="click" placement="bottom">
            <a-button type="ghost">
              <SettingOutlined />
            </a-button>
            <template #overlay>
              <a-card>
                <div>
                  <div class="text-gray-400 mb-4">
                    【{{ t('显示') }}/{{ t('隐藏') }} 】 {{ t('二维码') }}
                  </div>
                  <div>
                    <a-switch
                      v-model:checked="record.display"
                      checked-value="1"
                      unchecked-value="0"
                      @change="changeDisplay(record as Media)"
                    >
                      <template #checkedChildren>{{ t('显示') }}</template>
                      <template #unCheckedChildren>{{ t('隐藏') }}</template>
                    </a-switch>
                  </div>
                </div>
                <div class="mt-4">
                  <div class="text-gray-400 mb-4">【 {{ t('长链接') }}/{{ t('短链接') }} 】</div>
                  <div>
                    <a-switch
                      v-model:checked="record.conn"
                      checked-value="0"
                      unchecked-value="1"
                      @change="changeConnect(record as Media)"
                    >
                      <template #checkedChildren>{{ t('长链接') }}</template>
                      <template #unCheckedChildren>{{ t('短链接') }}</template>
                    </a-switch>
                  </div>
                </div>
              </a-card>
            </template>
          </a-dropdown>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { formatColumns, notify } from '@/utils/common/common';
import { columnsRef } from '../data/columns';
import { list, edit, remove, changeDisplay, changeConnect } from '../data/curd';
import { query, table } from '../data/data';
import { form } from '../data/form';
import { useArrayFilter } from '@vueuse/core';
import type { TablePaginationConfig } from 'ant-design-vue';
import type { FilterValue, SorterResult } from 'ant-design-vue/es/table/interface';
import DataHead from './data-head.vue';
import type { Media } from '@/api/modules/lcd/lcd-device';
import { gotoRouter } from '@/router/utils';
import { labelOptions } from '../data/options';
import { labelGroup } from '@/api/modules/lcd/lcd-device';
import type { SettingOutlined } from '@ant-design/icons-vue';

const { t } = useI18n();
/* 行事件 */
const customRow = (record: any) => {
  return {
    onClick() {
      let rowKey = table.value.rowKey;
      const id = (record as any)[rowKey];
      form.value = record;
      if (!table.value.keys.includes(id)) {
        table.value.keys.push(id);
      } else {
        table.value.keys = useArrayFilter(table.value.keys, e => e !== id).value;
      }
      table.value.keys = [id];
    },

    onDblclick() {
      edit();
    },
  };
};

/* 分页事件触发 */
const pageChange = (
  pagination: TablePaginationConfig,
  filters: Record<string, FilterValue>,
  sorter: SorterResult<any> | SorterResult<any>[],
) => {
  if (pagination.current && pagination.pageSize) {
    query.value.pageNum = pagination.current;
    query.value.pageSize = pagination.pageSize;
  }
  if (!(sorter instanceof Array)) {
    query.value.isAsc = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  list();
};
const distribution = (record: Media) => {
  gotoRouter(`lcd-distribution`, {
    mediaId: record.mediaId,
  });
};

const changeGroup = async (record: Media) => {
  if (typeof record.label === 'object') {
    let label: string = record.label.join(',');
    if (label.startsWith(',')) {
      label = label.slice(1);
    }
    const { data } = await labelGroup({
      label,
      mediaIds: [record.mediaId],
    });
    notify(data);
    list();
  }
};
const computedColumns = computed(() =>
  columnsRef.value.map(e => {
    e.title = t(e.title);
    return e;
  }),
);
</script>

<style lang="scss" scoped></style>
